'use client';

import { useState, useEffect } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useTranslation } from 'react-i18next';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { DashboardLayout } from '@/components/layout/dashboard-layout';
import { AdminGuard } from '@/components/auth/PermissionGuard';
import { formatAddress, formatDate, formatCurrency } from '@/lib/utils';
import { multiChainApi } from '@/lib/multi-chain-api';
import { API_ENDPOINTS } from '@/config/api';
import { useWeb3 } from '@/hooks/useWeb3';
import { useVestingContract } from '@/hooks/useVestingContract';
import { useChain } from '@/context/ChainContext';
import { 
  Users, TrendingUp, Lock, CheckCircle, 
  XCircle, AlertCircle, Plus, PieChart,
  Calendar, Clock, UserPlus, Wallet, Shield,
  RefreshCw, ExternalLink
} from 'lucide-react';
import toast from 'react-hot-toast';

// Contract-based interfaces
interface ContractVestingInfo {
  vesting_duration_months: number;
  stats: {
    total_schedules: number;
    total_vesting_formatted: string;
    total_released_formatted: string;
    contract_balance_formatted: string;
  };
  categories: Record<string, {
    limit_formatted: string;
    allocated_formatted: string;
    remaining_formatted: string;
  }>;
}

interface VestingSchedule {
  schedule_id: string;
  beneficiary: string;
  total_amount_formatted: string;
  released_amount_formatted: string;
  releasable_amount_formatted: string;
  start_time_iso: string;
  revoked: boolean;
  category: string;
}

interface NewVestingRequest {
  beneficiaries: string[];
  amounts: string[];
  categories: string[];
}

const getCategoryDetails = (t: any) => ({
  founding: {
    label: t('allocations.categories.founding'),
    description: t('allocations.categoryDescriptions.founding'),
    color: 'bg-purple-100 text-purple-800'
  },
  technical: {
    label: t('allocations.categories.technical'), 
    description: t('allocations.categoryDescriptions.technical'),
    color: 'bg-blue-100 text-blue-800'
  },
  operations: {
    label: t('allocations.categories.operations'),
    description: t('allocations.categoryDescriptions.operations'),
    color: 'bg-green-100 text-green-800'
  },
  institutional: {
    label: t('allocations.categories.institutional'),
    description: t('allocations.categoryDescriptions.institutional'),
    color: 'bg-orange-100 text-orange-800'
  }
});

export default function VestingAllocationsPage() {
  const { t } = useTranslation('vesting');
  const queryClient = useQueryClient();
  const { currentChain } = useChain();
  const [showCreateModal, setShowCreateModal] = useState(false);
  const [selectedCategory, setSelectedCategory] = useState<string>('');
  const [allSchedules, setAllSchedules] = useState<VestingSchedule[]>([]);
  const [vestingContractAddress, setVestingContractAddress] = useState<string>('');
  const [revokingScheduleId, setRevokingScheduleId] = useState<string | null>(null);
  
  const categoryDetails = getCategoryDetails(t);
  
  // Web3 hooks
  const { provider, account, isConnected, connect } = useWeb3();
  // Only initialize vesting contract hook when we have the address
  const vestingContract = useVestingContract(vestingContractAddress || '');

  // Fetch contract addresses first
  const { data: contractAddresses } = useQuery({
    queryKey: ['contractAddresses', currentChain],
    queryFn: async () => {
      const client = multiChainApi.getClient(currentChain);
      const response = await client.get(API_ENDPOINTS.contracts.info);
      return response.data.addresses;
    },
  });

  // Set vesting contract address when available
  useEffect(() => {
    if (contractAddresses?.dtv_vesting) {
      setVestingContractAddress(contractAddresses.dtv_vesting);
    }
  }, [contractAddresses]);

  // Fetch contract vesting information
  const { data: contractInfo, isLoading: contractLoading, refetch } = useQuery({
    queryKey: ['contractVestingInfo', currentChain],
    queryFn: async () => {
      const client = multiChainApi.getClient(currentChain);
      const response = await client.get(API_ENDPOINTS.contracts.info);
      return response.data.vesting as ContractVestingInfo;
    },
    refetchInterval: 30000
  });

  // Fetch all vesting schedules
  const { data: allSchedulesData, isLoading: schedulesLoading } = useQuery({
    queryKey: ['allVestingSchedules', currentChain],
    queryFn: async () => {
      const client = multiChainApi.getClient(currentChain);
      const response = await client.get(API_ENDPOINTS.contracts.vesting.allSchedules);
      return response.data;
    },
    refetchInterval: 30000
  });

  // Web3 Create vesting schedule mutation
  const createVestingMutation = useMutation({
    mutationFn: async (data: NewVestingRequest) => {
      if (!isConnected) {
        throw new Error('Please connect your wallet first');
      }
      
      if (!provider) {
        throw new Error('Web3 provider not available. Please ensure MetaMask is connected.');
      }
      
      if (!vestingContractAddress) {
        throw new Error('Vesting contract address not loaded yet');
      }
      
      // Check ownership first
      const ownershipInfo = await vestingContract.checkOwnership();
      if (!ownershipInfo.isOwner) {
        throw new Error('Only the contract owner can create vesting schedules');
      }
      
      return await vestingContract.createVestingSchedules(
        data.beneficiaries,
        data.amounts,
        data.categories
      );
    },
    onSuccess: (result) => {
      if (result.success) {
        toast.success(t('allocations.success.schedulesCreated'));
        setShowCreateModal(false);
        setTimeout(() => {
          refetch();
          queryClient.invalidateQueries({ queryKey: ['allVestingSchedules', currentChain] });
        }, 3000); // Wait 3 seconds for blockchain to update
      }
    },
    onError: (error: any) => {
      console.error('Create vesting error:', error);
      toast.error(error.message || t('allocations.errors.createFailed'));
    }
  });

  // Web3 Revoke vesting schedule mutation
  const revokeVestingMutation = useMutation({
    mutationFn: async (scheduleId: string) => {
      if (!isConnected) {
        throw new Error('Please connect your wallet first');
      }
      
      if (!provider) {
        throw new Error('Web3 provider not available. Please ensure MetaMask is connected.');
      }
      
      if (!vestingContractAddress) {
        throw new Error('Vesting contract address not loaded yet');
      }
      
      // Check ownership first
      const ownershipInfo = await vestingContract.checkOwnership();
      if (!ownershipInfo.isOwner) {
        throw new Error('Only the contract owner can revoke vesting schedules');
      }
      
      return await vestingContract.revokeVestingSchedule(scheduleId);
    },
    onSuccess: (result) => {
      if (result.success) {
        toast.success(t('allocations.success.scheduleRevoked'));
        setRevokingScheduleId(null);
        setTimeout(() => {
          refetch();
          queryClient.invalidateQueries({ queryKey: ['allVestingSchedules', currentChain] });
        }, 3000); // Wait 3 seconds for blockchain to update
      }
    },
    onError: (error: any) => {
      console.error('Revoke vesting error:', error);
      toast.error(error.message || t('allocations.errors.revokeFailed'));
      setRevokingScheduleId(null);
    }
  });

  const getCategoryUtilization = (category: string) => {
    if (!contractInfo?.categories[category]) return 0;
    const allocated = parseFloat(contractInfo.categories[category].allocated_formatted);
    const limit = parseFloat(contractInfo.categories[category].limit_formatted);
    return limit > 0 ? (allocated / limit) * 100 : 0;
  };

  const handleConnectWallet = async () => {
    const connected = await connect();
    if (connected) {
      toast.success(t('common.success'));
    }
  };

  return (
    <DashboardLayout>
      <AdminGuard>
        <div className="space-y-6">
          {/* Header */}
          <div className="flex items-center justify-between">
            <div>
              <h1 className="text-3xl font-bold">{t('allocations.title')}</h1>
              <p className="text-muted-foreground">
                {t('allocations.subtitle')}
              </p>
            </div>
            <div className="flex gap-2">
              {!isConnected ? (
                <Button
                  onClick={handleConnectWallet}
                  className="flex items-center gap-2"
                >
                  <Wallet className="h-4 w-4" />
                  Connect Wallet
                </Button>
              ) : (
                <div className="flex items-center gap-2 px-3 py-2 bg-green-100 text-green-800 rounded-md text-sm">
                  <CheckCircle className="h-4 w-4" />
                  <span>Wallet Connected</span>
                </div>
              )}
              <Button
                variant="outline"
                onClick={() => {
                  refetch();
                  queryClient.invalidateQueries({ queryKey: ['allVestingSchedules', currentChain] });
                }}
                disabled={contractLoading || schedulesLoading}
              >
                <RefreshCw className={`h-4 w-4 mr-2 ${(contractLoading || schedulesLoading) ? 'animate-spin' : ''}`} />
                Refresh
              </Button>
              <Button 
                onClick={() => setShowCreateModal(true)}
                disabled={!isConnected}
              >
                <Plus className="h-4 w-4 mr-2" />
                Create Vesting Schedule
              </Button>
            </div>
          </div>

          {contractLoading ? (
            <div className="flex items-center justify-center h-64">
              <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600"></div>
            </div>
          ) : (
            <>
              {/* Overview Stats */}
              <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
                <Card>
                  <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                    <CardTitle className="text-sm font-medium">{t('allocations.stats.totalSchedules')}</CardTitle>
                    <Calendar className="h-4 w-4 text-muted-foreground" />
                  </CardHeader>
                  <CardContent>
                    <div className="text-2xl font-bold">
                      {contractInfo?.stats.total_schedules || 0}
                    </div>
                    <p className="text-xs text-muted-foreground">
                      {t('allocations.stats.totalSchedulesDesc')}
                    </p>
                  </CardContent>
                </Card>

                <Card>
                  <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                    <CardTitle className="text-sm font-medium">{t('allocations.stats.totalVesting')}</CardTitle>
                    <Lock className="h-4 w-4 text-blue-600" />
                  </CardHeader>
                  <CardContent>
                    <div className="text-2xl font-bold">
                      {formatCurrency(parseFloat(contractInfo?.stats.total_vesting_formatted || '0'), 'DTV')}
                    </div>
                    <p className="text-xs text-muted-foreground">
                      {t('allocations.stats.totalVestingDesc')}
                    </p>
                  </CardContent>
                </Card>

                <Card>
                  <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                    <CardTitle className="text-sm font-medium">{t('allocations.stats.totalReleased')}</CardTitle>
                    <CheckCircle className="h-4 w-4 text-green-600" />
                  </CardHeader>
                  <CardContent>
                    <div className="text-2xl font-bold">
                      {formatCurrency(parseFloat(contractInfo?.stats.total_released_formatted || '0'), 'DTV')}
                    </div>
                    <p className="text-xs text-muted-foreground">
                      {t('allocations.stats.totalReleasedDesc')}
                    </p>
                  </CardContent>
                </Card>

                <Card>
                  <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                    <CardTitle className="text-sm font-medium">{t('allocations.stats.contractBalance')}</CardTitle>
                    <Wallet className="h-4 w-4 text-purple-600" />
                  </CardHeader>
                  <CardContent>
                    <div className="text-2xl font-bold">
                      {formatCurrency(parseFloat(contractInfo?.stats.contract_balance_formatted || '0'), 'DTV')}
                    </div>
                    <p className="text-xs text-muted-foreground">
                      {t('allocations.stats.contractBalanceDesc')}
                    </p>
                  </CardContent>
                </Card>
              </div>

              {/* Vesting Categories */}
              <Card>
                <CardHeader>
                  <CardTitle>{t('allocations.categoryCard.title')}</CardTitle>
                  <CardDescription>
                    {t('allocations.categoryCard.subtitle', { months: contractInfo?.vesting_duration_months || 84 })}
                  </CardDescription>
                </CardHeader>
                <CardContent>
                  <div className="space-y-4">
                    {contractInfo && Object.entries(contractInfo.categories).map(([category, data]) => {
                      const details = categoryDetails[category as keyof typeof categoryDetails];
                      const utilizationPercentage = getCategoryUtilization(category);
                      
                      // Count revoked schedules for this category
                      const categorySchedules = allSchedulesData?.schedules?.filter((s: VestingSchedule) => s.category === category) || [];
                      const revokedCount = categorySchedules.filter((s: VestingSchedule) => s.revoked).length;
                      const activeCount = categorySchedules.filter((s: VestingSchedule) => !s.revoked).length;
                      
                      return (
                        <div key={category} className="space-y-3 p-4 border rounded-lg">
                          <div className="flex items-center justify-between">
                            <div className="flex items-center gap-3">
                              <span className={`px-3 py-1 rounded-full text-sm font-medium ${details?.color || 'bg-gray-100 text-gray-800'}`}>
                                {details?.label || category}
                              </span>
                              <div>
                                <p className="text-sm text-muted-foreground">
                                  {details?.description || `${category} allocation`}
                                </p>
                                <p className="text-xs text-muted-foreground mt-1">
                                  {t('allocations.categoryCard.vestingInfo', { months: contractInfo.vesting_duration_months })}
                                  {categorySchedules.length > 0 && (
                                    <span className="ml-2">
                                      • {t('allocations.categoryCard.activeSchedules', { active: activeCount })}{revokedCount > 0 && t('allocations.categoryCard.revokedSchedules', { revoked: revokedCount })}
                                    </span>
                                  )}
                                </p>
                              </div>
                            </div>
                            <div className="text-right">
                              <p className="font-medium">{formatCurrency(parseFloat(data.limit_formatted), 'DTV')}</p>
                              <p className="text-sm text-muted-foreground">{t('allocations.categoryCard.categoryLimit')}</p>
                            </div>
                          </div>
                          
                          <div className="space-y-1">
                            <div className="flex justify-between text-sm">
                              <span>{t('allocations.categoryCard.allocated')}</span>
                              <span>{utilizationPercentage.toFixed(1)}%</span>
                            </div>
                            <div className="w-full bg-gray-200 rounded-full h-2">
                              <div
                                className="bg-blue-600 h-2 rounded-full"
                                style={{ width: `${utilizationPercentage}%` }}
                              />
                            </div>
                          </div>

                          <div className="grid grid-cols-3 gap-4 text-sm">
                            <div>
                              <label className="text-muted-foreground">{t('allocations.categoryCard.allocated')}</label>
                              <p className="font-medium">{formatCurrency(parseFloat(data.allocated_formatted), 'DTV')}</p>
                            </div>
                            <div>
                              <label className="text-muted-foreground">{t('allocations.categoryCard.remaining')}</label>
                              <p className="font-medium">{formatCurrency(parseFloat(data.remaining_formatted), 'DTV')}</p>
                            </div>
                            <div>
                              <label className="text-muted-foreground">{t('allocations.categoryCard.available')}</label>
                              <p className="font-medium text-green-600">
                                {formatCurrency(parseFloat(data.remaining_formatted), 'DTV')}
                              </p>
                            </div>
                          </div>

                          {parseFloat(data.remaining_formatted) > 0 && (
                            <Button
                              size="sm"
                              onClick={() => {
                                setSelectedCategory(category);
                                setShowCreateModal(true);
                              }}
                            >
                              <UserPlus className="h-4 w-4 mr-2" />
                              {t('allocations.categoryCard.createSchedule')}
                            </Button>
                          )}
                        </div>
                      );
                    })}
                  </div>
                </CardContent>
              </Card>

              {/* Contract Information */}
              <Card>
                <CardHeader>
                  <CardTitle className="flex items-center gap-2">
                    <Shield className="h-5 w-5" />
                    {t('allocations.contractInfo.title')}
                  </CardTitle>
                  <CardDescription>{t('allocations.contractInfo.subtitle')}</CardDescription>
                </CardHeader>
                <CardContent>
                  <div className="grid grid-cols-2 md:grid-cols-4 gap-4 text-sm">
                    <div>
                      <label className="text-muted-foreground">{t('allocations.contractInfo.contractType')}</label>
                      <p className="font-medium">{t('allocations.contractInfo.contractTypeValue')}</p>
                    </div>
                    <div>
                      <label className="text-muted-foreground">{t('allocations.contractInfo.vestingDuration')}</label>
                      <p className="font-medium">{contractInfo?.vesting_duration_months} {t('allocations.contractInfo.months')}</p>
                    </div>
                    <div>
                      <label className="text-muted-foreground">{t('allocations.contractInfo.cliffPeriod')}</label>
                      <p className="font-medium">{t('allocations.contractInfo.cliffPeriodValue')}</p>
                    </div>
                    <div>
                      <label className="text-muted-foreground">{t('allocations.contractInfo.releaseType')}</label>
                      <p className="font-medium">{t('allocations.contractInfo.releaseTypeValue')}</p>
                    </div>
                  </div>
                  <div className="mt-4 space-y-2">
                    <div className="p-3 bg-blue-50 rounded-lg">
                      <p className="text-sm text-blue-800">
                        <strong>{t('allocations.contractInfo.security')}:</strong> {t('allocations.contractInfo.securityMessage')}
                      </p>
                    </div>
                    <div className="p-3 bg-yellow-50 rounded-lg">
                      <p className="text-sm text-yellow-800">
                        <strong>{t('allocations.contractInfo.important')}:</strong> {t('allocations.contractInfo.importantMessage')}
                      </p>
                    </div>
                  </div>
                </CardContent>
              </Card>

              {/* All Vesting Schedules */}
              <Card>
                <CardHeader>
                  <CardTitle className="flex items-center gap-2">
                    <Users className="h-5 w-5" />
                    {t('allocations.allSchedules.title')}
                  </CardTitle>
                  <CardDescription>
                    {t('allocations.allSchedules.subtitle')}
                  </CardDescription>
                </CardHeader>
                <CardContent>
                  {schedulesLoading ? (
                    <div className="flex items-center justify-center h-32">
                      <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
                    </div>
                  ) : allSchedulesData?.schedules?.length > 0 ? (
                    <div className="overflow-x-auto">
                      <table className="w-full border-collapse">
                        <thead>
                          <tr className="border-b">
                            <th className="text-left p-2">{t('allocations.allSchedules.table.beneficiary')}</th>
                            <th className="text-left p-2">{t('allocations.allSchedules.table.category')}</th>
                            <th className="text-right p-2">{t('allocations.allSchedules.table.totalAmount')}</th>
                            <th className="text-right p-2">{t('allocations.allSchedules.table.released')}</th>
                            <th className="text-right p-2">{t('allocations.allSchedules.table.releasable')}</th>
                            <th className="text-left p-2">{t('allocations.allSchedules.table.startDate')}</th>
                            <th className="text-center p-2">{t('allocations.allSchedules.table.status')}</th>
                            <th className="text-center p-2">{t('allocations.allSchedules.table.actions')}</th>
                          </tr>
                        </thead>
                        <tbody>
                          {allSchedulesData.schedules.map((schedule: VestingSchedule) => {
                            const details = categoryDetails[schedule.category as keyof typeof categoryDetails];
                            return (
                              <tr key={schedule.schedule_id} className="border-b hover:bg-gray-50">
                                <td className="p-2">
                                  <a
                                    href={`https://${currentChain === 'mainnet' ? '' : 'testnet.'}bscscan.com/address/${schedule.beneficiary}`}
                                    target="_blank"
                                    rel="noopener noreferrer"
                                    className="text-blue-600 hover:underline flex items-center gap-1"
                                  >
                                    {formatAddress(schedule.beneficiary)}
                                    <ExternalLink className="h-3 w-3" />
                                  </a>
                                </td>
                                <td className="p-2">
                                  <span className={`px-2 py-1 rounded-full text-xs font-medium ${details?.color || 'bg-gray-100 text-gray-800'}`}>
                                    {details?.label || schedule.category}
                                  </span>
                                </td>
                                <td className="p-2 text-right font-medium">
                                  {formatCurrency(parseFloat(schedule.total_amount_formatted), 'DTV')}
                                </td>
                                <td className="p-2 text-right">
                                  {formatCurrency(parseFloat(schedule.released_amount_formatted), 'DTV')}
                                </td>
                                <td className="p-2 text-right text-green-600">
                                  {formatCurrency(parseFloat(schedule.releasable_amount_formatted), 'DTV')}
                                </td>
                                <td className="p-2">
                                  {formatDate(schedule.start_time_iso)}
                                </td>
                                <td className="p-2 text-center">
                                  {schedule.revoked ? (
                                    <span className="inline-flex items-center gap-1 px-2 py-1 bg-red-100 text-red-800 rounded-full text-xs">
                                      <XCircle className="h-3 w-3" />
                                      {t('allocations.allSchedules.status.revoked')}
                                    </span>
                                  ) : (
                                    <span className="inline-flex items-center gap-1 px-2 py-1 bg-green-100 text-green-800 rounded-full text-xs">
                                      <CheckCircle className="h-3 w-3" />
                                      {t('allocations.allSchedules.status.active')}
                                    </span>
                                  )}
                                </td>
                                <td className="p-2 text-center">
                                  <div className="flex items-center justify-center gap-2">
                                    <Button
                                      size="sm"
                                      variant="ghost"
                                      onClick={() => {
                                        navigator.clipboard.writeText(schedule.schedule_id);
                                        toast.success(t('allocations.allSchedules.scheduleIdCopied'));
                                      }}
                                      title={t('allocations.allSchedules.copyScheduleId')}
                                    >
                                      <Shield className="h-4 w-4" />
                                    </Button>
                                    {!schedule.revoked && (
                                      <Button
                                        size="sm"
                                        variant="ghost"
                                        className="text-red-600 hover:text-red-700"
                                        disabled={revokingScheduleId === schedule.schedule_id || !isConnected || !vestingContractAddress}
                                        onClick={() => {
                                          if (!isConnected) {
                                            toast.error('Please connect your wallet first');
                                            return;
                                          }
                                          
                                          if (!vestingContractAddress) {
                                            toast.error('Vesting contract not initialized');
                                            return;
                                          }
                                          
                                          if (confirm(`Are you sure you want to revoke this vesting schedule?\n\nBeneficiary: ${formatAddress(schedule.beneficiary)}\nAmount: ${formatCurrency(parseFloat(schedule.total_amount_formatted), 'DTV')}\n\nThis action cannot be undone.`)) {
                                            setRevokingScheduleId(schedule.schedule_id);
                                            revokeVestingMutation.mutate(schedule.schedule_id);
                                          }
                                        }}
                                        title={!isConnected ? t('allocations.allSchedules.connectToRevoke') : !vestingContractAddress ? t('allocations.allSchedules.loadingContract') : t('allocations.allSchedules.revokeSchedule')}
                                      >
                                        {revokingScheduleId === schedule.schedule_id ? (
                                          <RefreshCw className="h-4 w-4 animate-spin" />
                                        ) : (
                                          <XCircle className="h-4 w-4" />
                                        )}
                                      </Button>
                                    )}
                                  </div>
                                </td>
                              </tr>
                            );
                          })}
                        </tbody>
                      </table>
                      
                      {/* Category Summary */}
                      {allSchedulesData.categories_summary && Object.keys(allSchedulesData.categories_summary).length > 0 && (
                        <div className="mt-6 p-4 bg-gray-50 rounded-lg">
                          <h4 className="font-medium mb-3">{t('allocations.allSchedules.categorySummary')}</h4>
                          <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                            {Object.entries(allSchedulesData.categories_summary).map(([category, summary]: [string, any]) => {
                              const details = categoryDetails[category as keyof typeof categoryDetails];
                              return (
                                <div key={category} className="space-y-1">
                                  <span className={`inline-block px-2 py-1 rounded-full text-xs font-medium ${details?.color || 'bg-gray-100 text-gray-800'}`}>
                                    {details?.label || category}
                                  </span>
                                  <p className="text-xs text-muted-foreground">
                                    {t('allocations.allSchedules.scheduleCount', { active: summary.active_count, total: summary.schedule_count })}
                                  </p>
                                  <p className="text-sm font-medium">
                                    {formatCurrency(parseFloat(summary.total_amount_formatted), 'DTV')}
                                  </p>
                                </div>
                              );
                            })}
                          </div>
                        </div>
                      )}
                    </div>
                  ) : (
                    <div className="text-center py-8 text-muted-foreground">
                      <Users className="h-12 w-12 mx-auto mb-4 opacity-30" />
                      <p>{t('allocations.allSchedules.noSchedules')}</p>
                    </div>
                  )}
                </CardContent>
              </Card>
            </>
          )}

          {/* Create Vesting Schedule Modal */}
          {showCreateModal && (
            <CreateVestingModal
              selectedCategory={selectedCategory}
              contractInfo={contractInfo}
              onClose={() => {
                setShowCreateModal(false);
                setSelectedCategory('');
              }}
              onSubmit={(data) => createVestingMutation.mutate(data)}
              isLoading={createVestingMutation.isPending}
              isConnected={isConnected}
              account={account}
              onConnectWallet={handleConnectWallet}
            />
          )}
        </div>
      </AdminGuard>
    </DashboardLayout>
  );
}

// Create Vesting Modal Component
function CreateVestingModal({
  selectedCategory,
  contractInfo,
  onClose,
  onSubmit,
  isLoading,
  isConnected,
  account,
  onConnectWallet
}: {
  selectedCategory: string;
  contractInfo?: ContractVestingInfo;
  onClose: () => void;
  onSubmit: (data: NewVestingRequest) => void;
  isLoading: boolean;
  isConnected: boolean;
  account: string | null;
  onConnectWallet: () => void;
}) {
  const { t } = useTranslation('vesting');
  const categoryDetails = getCategoryDetails(t);
  const [beneficiaries, setBeneficiaries] = useState(['']);
  const [amounts, setAmounts] = useState(['']);
  const [categories, setCategories] = useState([selectedCategory || 'founding']);

  const addBeneficiary = () => {
    setBeneficiaries([...beneficiaries, '']);
    setAmounts([...amounts, '']);
    setCategories([...categories, selectedCategory || 'founding']);
  };

  const removeBeneficiary = (index: number) => {
    setBeneficiaries(beneficiaries.filter((_, i) => i !== index));
    setAmounts(amounts.filter((_, i) => i !== index));
    setCategories(categories.filter((_, i) => i !== index));
  };

  const updateBeneficiary = (index: number, value: string) => {
    const newBeneficiaries = [...beneficiaries];
    newBeneficiaries[index] = value;
    setBeneficiaries(newBeneficiaries);
  };

  const updateAmount = (index: number, value: string) => {
    const newAmounts = [...amounts];
    newAmounts[index] = value;
    setAmounts(newAmounts);
  };

  const updateCategory = (index: number, value: string) => {
    const newCategories = [...categories];
    newCategories[index] = value;
    setCategories(newCategories);
  };

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    
    // Validate data
    const validBeneficiaries = beneficiaries.filter(addr => addr.trim() !== '');
    const validAmounts = amounts.filter(amount => amount.trim() !== '' && parseFloat(amount) > 0);
    const validCategories = categories.slice(0, validBeneficiaries.length);

    if (validBeneficiaries.length === 0 || validBeneficiaries.length !== validAmounts.length) {
      toast.error('Please fill in all beneficiary addresses and amounts');
      return;
    }

    onSubmit({
      beneficiaries: validBeneficiaries,
      amounts: validAmounts,
      categories: validCategories
    });
  };

  const getRemainingForCategory = (category: string) => {
    if (!contractInfo?.categories[category]) return '0';
    return contractInfo.categories[category].remaining_formatted;
  };

  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50">
      <Card className="w-full max-w-2xl max-h-[80vh] overflow-y-auto">
        <CardHeader>
          <CardTitle>Create Vesting Schedule</CardTitle>
          <CardDescription>
            Create new vesting schedules on the blockchain
          </CardDescription>
        </CardHeader>
        <CardContent>
          <form onSubmit={handleSubmit} className="space-y-4">
            {beneficiaries.map((beneficiary, index) => (
              <div key={index} className="space-y-3 p-4 border rounded-lg">
                <div className="flex items-center justify-between">
                  <h4 className="font-medium">Beneficiary {index + 1}</h4>
                  {beneficiaries.length > 1 && (
                    <Button
                      type="button"
                      variant="ghost"
                      size="sm"
                      onClick={() => removeBeneficiary(index)}
                    >
                      <XCircle className="h-4 w-4" />
                    </Button>
                  )}
                </div>
                
                <div>
                  <label className="block text-sm font-medium mb-1">Wallet Address</label>
                  <input
                    type="text"
                    className="w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                    placeholder="0x..."
                    value={beneficiary}
                    onChange={(e) => updateBeneficiary(index, e.target.value)}
                    required
                  />
                </div>

                <div className="grid grid-cols-2 gap-3">
                  <div>
                    <label className="block text-sm font-medium mb-1">Amount (DTV)</label>
                    <input
                      type="number"
                      className="w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                      placeholder="1000000"
                      value={amounts[index]}
                      onChange={(e) => updateAmount(index, e.target.value)}
                      min="0"
                      step="1"
                      required
                    />
                  </div>
                  
                  <div>
                    <label className="block text-sm font-medium mb-1">Category</label>
                    <select
                      className="w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                      value={categories[index]}
                      onChange={(e) => updateCategory(index, e.target.value)}
                    >
                      {Object.entries(categoryDetails).map(([key, details]) => (
                        <option key={key} value={key}>
                          {details.label} (Available: {getRemainingForCategory(key)} DTV)
                        </option>
                      ))}
                    </select>
                  </div>
                </div>
              </div>
            ))}

            <Button
              type="button"
              variant="outline"
              onClick={addBeneficiary}
              className="w-full"
            >
              <Plus className="h-4 w-4 mr-2" />
              Add Another Beneficiary
            </Button>

            {!isConnected && (
              <div className="bg-red-50 p-3 rounded-lg">
                <div className="flex items-center justify-between">
                  <div>
                    <p className="text-sm text-red-800">
                      <strong>Wallet Required:</strong> You need to connect your wallet to create vesting schedules.
                    </p>
                  </div>
                  <Button
                    type="button"
                    size="sm"
                    onClick={onConnectWallet}
                    className="ml-3"
                  >
                    <Wallet className="h-4 w-4 mr-2" />
                    Connect Wallet
                  </Button>
                </div>
              </div>
            )}

            {isConnected && account && (
              <div className="bg-green-50 p-3 rounded-lg">
                <p className="text-sm text-green-800">
                  <strong>Wallet Connected:</strong> {formatAddress(account)}
                </p>
              </div>
            )}

            <div className="bg-yellow-50 p-3 rounded-lg">
              <p className="text-sm text-yellow-800">
                <strong>Web3 Transaction:</strong> Creating vesting schedules requires contract owner privileges 
                and will execute a transaction on the blockchain. Make sure all addresses are correct as 
                transactions cannot be undone.
              </p>
            </div>

            <div className="flex justify-end gap-2 pt-4">
              <Button type="button" variant="outline" onClick={onClose}>
                Cancel
              </Button>
              <Button type="submit" disabled={isLoading || !isConnected}>
                {isLoading ? (
                  <>
                    <RefreshCw className="h-4 w-4 mr-2 animate-spin" />
                    Processing Transaction...
                  </>
                ) : !isConnected ? (
                  <>
                    <Wallet className="h-4 w-4 mr-2" />
                    Connect Wallet to Create
                  </>
                ) : (
                  'Create Vesting Schedules (Web3)'
                )}
              </Button>
            </div>
          </form>
        </CardContent>
      </Card>
    </div>
  );
}